
module.exports = getBaiduToken =  () => {
    return new Promise(async(reslove,reject)=>{
        const { APP_ID, API_KEY, SECRET_KEY } = require('./baiduConfig')
        const fs = require('fs')
        let tokenStr = ''
        const axios = require('axios')
        const uri = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`
        try {
            tokenStr = fs.readFileSync('./baiduToken.txt')
            const token = JSON.parse(tokenStr)
            if (!token && Date.now() < token.exp) {
                const { data } = await axios.get(uri)
                // 设置token过期时间
                data.exp = data.expires_in + Date.now() - 60 * 10 * 1000
                reslove(data)
            } else {
                reslove(token)
            }
        } catch (error) {
            const { data } = await axios.get(uri)
            // 设置token过期时间
            data.exp = data.expires_in+ Date.now() - 60 * 10 * 1000
            fs.writeFileSync('./baiduToken.txt', JSON.stringify(data))
            reslove(data)
        }

    })

}